const router = require('koa-router')()
const util = require('../utils/util')
const log4js = require('../utils/log4j')
const jwt = require('jsonwebtoken')
const Menu = require('../models/menuSchema');

router.prefix('/menu');


router.post('/operate', async (ctx) => {
  const { _id, type, ...params } = ctx.request.body;
  let res;
  try {

    if (type === 'add') {
      res = await Menu.create(params)
      ctx.body = util.success('添加成功')
      return
    } else if (type === 'edit') {
      params.updateTime = new Date()
      res = await Menu.findByIdAndUpdate(_id, params)
      ctx.body = util.success('编辑成功')
      return
    } else if (type === 'delete') {
      await Menu.findByIdAndDelete(_id)
      await Menu.deleteMany({ parentId: { $in: _id } })
      ctx.body = util.success('删除成功')
      return
    }
  } catch (error) {
    console.error(error)
    ctx.body = util.fail(`修改失败 ${error.stack}`)
    return
  }
  ctx.body = util.success('')
})

router.get('/list', async ctx => {
  const { menuName, menuState } = ctx.request.query;
  const params = {}
  if (menuName) {
    params.menuName = new RegExp(menuName, 'i')
  }
  if (menuState) {
    params.menuState = menuState
  }
  try {
    let rootList = await Menu.find(params) || [];
    let list = util.getTreeMenu(rootList, null, [])
    ctx.body = util.success(list)
  } catch (error) {
    console.error(error)
  }
})

const getTreeMenu = (source, id, list) => {
  for (const item of source) {
    if (item.parentId.slice().pop() === (id ? id.toString() : id)) {
      list.push(item._doc)
    }
  }
  list.forEach(item => {
    item.children = [];
    getTreeMenu(source, item._id, item.children);
    if (item.children.length === 0) {
      delete item.children;
    } else if (item.children.length > 0 && item.children[0].menuType === 2) {
      item.action = item.children;
    }
  })
  return list
}

module.exports = router;
